from jenkinsapi.jenkins import Jenkins
from jenkinsapi.build import Build


class Jenkins_util:
    def __init__(self, jenkins_url, username, password, job_name, git_url, branch, parameters=None):
        if parameters==None:
            self.parameters = {"Branch":branch}
        else:
            self.parameters=parameters
        self.lastBuildNumber = None
        self.git_url = git_url
        self.jenkins_url = jenkins_url
        self.username = username
        self.password = password
        self.job_name = job_name
        self.branch = branch
        self.jenkins = Jenkins(self.jenkins_url, self.username, self.password)
        self.job_instance = self.jenkins.get_job(self.job_name)

    def build_job(self):
        try:
            self.jenkins.build_job(self.job_name, self.parameters)
        except:
            return False

        return True

    def job_status(self):
        flag = self.job_instance.is_queued_or_running()
        return flag

    def job_last_build_info(self):

        self.job_instance = self.jenkins.get_job(self.job_name)
        result = {"code": "0", "status": "", "branch": "", "job_name": self.job_name, "message": ""}
        if not self.job_instance.__dict__['_data'].get("lastBuild"):
            result["message"] = '系统异常，未获取到该job的lastBuild信息。'
            return result
        url = self.job_instance.__dict__['_data']['lastBuild']['url']
        number = self.job_instance.__dict__['_data']['lastBuild']['number']
        try:
            obj = Build(url, number, self.job_instance)
            result["status"] = obj.get_status()
            result["branch"] = obj.get_revision_branch()[0]["name"]
        except:
            result["message"] = '系统异常，未获取到该job的构建信息。'

        return result

    def client_build_upload_path(self):
        # print('upload file root path:', path)
        # print('upload file:', '|'.join(routeName))
        self.job_instance = self.jenkins.get_job(self.job_name)

        import re
        root_path_reg = re.compile('^(.*)upload file root path:(.*)\n', re.M)
        console = self.job_instance.get_console()
        root_path = root_path_reg.search(console).groups()[1]
        path_reg = re.compile('^(.*)upload file:(.*)\n', re.M)
        path = path_reg.search(console).groups()[1].split("|")

        return


if __name__ == '__main__':
    j = Jenkins_util(jenkins_url="http://192.168.2.92:8080/", username="", password="",
                     job_name='windows-client-build', git_url='', branch='',
                     parameters={"name": "sha1", "value": "*/dev_std"})
    print(j.job_status())
